<template>
  <h3>{{ pList.title }}</h3>
  <div id="section">
    <bSearch :instance="mSearch">
      <el-button @click="() => mSearch.onLast()" :disabled="mSearch.history_length <= 1">上次查询</el-button>
      <el-button @click="() => mSearch.onSearch()" type="primary">搜索</el-button>
    </bSearch>
    <div class="blank"></div>
    <bTableVue :instance="pList"></bTableVue>
    <el-dialog v-model="dForm._show" :title="dForm.title" style="width: 600px" :destroy-on-close="true">
      <bForm :instance="dForm" cover="100%">
        <el-button @click="onUpdate">完成</el-button>
      </bForm>
    </el-dialog>
    <el-dialog v-model="dForm.showIcon" :title="dForm.title" :destroy-on-close="true">
      <ElRadioGroup v-model="dForm.data.icon" @change="dForm.showIcon = false">
        <ElRadioButton v-for="item in includeRemove" :key="item.name" :label="item.name" :value="item.name"
          :title="item.name">
          <ElIcon>
            <component v-if="item.name" :is="item" />
          </ElIcon>
        </ElRadioButton>
      </ElRadioGroup>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Menulist, MenuSearch, MenuForm } from "@b/index/menu";
import bSearch from "@/components/public/b_search.vue";
import bTableVue from "@/components/public/b_table.vue";
import bForm from "@/components/public/b_form.vue";
import { ElDialog, ElButton, ElRadioButton, ElRadioGroup, ElIcon } from "element-plus";
import *as icons from "@element-plus/icons-vue";
import { headStore } from "@b/store";

const pList = new Menulist();
const mSearch = new MenuSearch();
const dForm = new MenuForm();

pList.init();
mSearch.init();

const includeRemove = Object.assign({
  _remove: { name: "" }
}, icons)

mSearch.onSearch = () => {
  //解构（浅拷贝，防止存在查询条件时点击页码产生的混乱）
  const search_key = mSearch.getData();
  //保存查询条件
  mSearch.history.push(search_key);
  mSearch.history_length = mSearch.history.length;
  pList.search_key = search_key;
  pList.refresh(1);
};

pList.onSearchWithParent = (id) => {
  mSearch.data.parentId = id
}

pList.onShowEdit = (id: number) => {
  if (!id) return
  dForm._show = true;
  dForm.id = id;
  dForm.setData();
};

pList.add = () => {
  dForm._show = true;
  dForm.title = "添加菜单";
};

pList.onAddChild = (id: number) => {
  dForm._show = true
  dForm.title = "添加菜单";
  dForm.data.parent = { id }
}

const onUpdate = async () => {
  const res = await dForm.updateData();
  if (res) {
    await headStore().getMemu('recache')
    dForm._show = false;
    pList.refresh();
  }
};
</script>

<style scoped>
:deep(.van-icon__image) {
  width: 40px;
  height: 40px;
}
</style>
